/*
 * $Id$
 */
package corejs.parser;

import corejs.Token;

import corejs.expr.Expression;
import corejs.expr.IncrementExpr;
import corejs.expr.DecrementExpr;
import corejs.expr.NotExpr;
import corejs.expr.SignedExpr;
import corejs.expr.TypeofExpr;

import static corejs.JsTokenType.*;

/**
 *
 * @author myang
 */
public class PrefixOperatorParser implements PrefixParser {

   private int _precedence;

   public PrefixOperatorParser(final int precedence) {
      _precedence = precedence;
   }

   public PrefixOperatorParser() {
      this(Precedence.PREFIX);
   }

   @Override
   public Expression expr(final PrattParser parser, final Token tk) {
      final Expression right = parser.expr(_precedence);
      return tk.is(BANG)        ? new NotExpr(right)
         :   tk.is(PLUS)        ? new SignedExpr(right)
         :   tk.is(MINUS)       ? new SignedExpr(right).neg()
         :   tk.is(TYPEOF)      ? new TypeofExpr(right)
         :   tk.is(PLUS_PLUS)   ? new IncrementExpr(right, true)
         :   tk.is(MINUS_MINUS) ? new DecrementExpr(right, true)
         :                        error(tk);
   }
   
   private Expression error(final Token tk) {
      throw new SyntaxError(tk);
   }
   
}
